package TCP.TCP4;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class TcpEchoServer {
    public ServerSocket listenSocket = null;
    //绑定服务器端口号
    public TcpEchoServer (int port) throws IOException {
        listenSocket = new ServerSocket(port);
    }
    //启动服务器
    public void start() throws IOException {
        System.out.println("服务器启动！");
        //线程池完成多来连接多服务
        ExecutorService service = Executors.newCachedThreadPool();
        while(true) {
            //接收客户端连接，没有来来连接就阻塞等待
            Socket clientSocket = listenSocket.accept();
            service.submit(new Runnable() {
                @Override
                public void run() {
                    try {
                        processService(clientSocket);
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            });
        }
    }
    private void processService(Socket clientSocket) throws IOException {
        System.out.printf("[%s : %s] 客户端上线\n", clientSocket.getInetAddress().toString(),
                clientSocket.getPort());
        try(InputStream inputStream = clientSocket.getInputStream();
            OutputStream outputStream = clientSocket.getOutputStream()) {
            while(true) {
                //1.服务器解析接收响应
                //检测服务端是否断开连接
                Scanner scanner = new Scanner(inputStream);
                if(!scanner.hasNext()) {
                    System.out.printf("[%s : %s] 客户端下线\n", clientSocket.getInetAddress().toString(),
                            clientSocket.getPort());
                    break;
                }
                String request = scanner.next();
                //2.根据请求计算响应
                String response = responseServer(request);
                //3.将响应返回给客户端
                PrintWriter printWriter = new PrintWriter(outputStream);
                printWriter.println(response);//IP协议结尾需要加\n，否则发不出去
                //刷新缓冲区
                printWriter.flush();
                //4.打印日志
                System.out.printf("[%s : %s] req: %s, resp: %s\n",clientSocket.getInetAddress().toString(),
                        clientSocket.getPort(), request, response);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            //释放空间，防止文字描述符占满
            clientSocket.close();
        }
    }
    //这是一个回显服务器
    private String responseServer(String request) {
        return request;
    }
    public static void main(String[] args) throws IOException {
        TcpEchoServer server = new TcpEchoServer(9090);
        server.start();
    }

}
